/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file    usart.c
  * @brief   This file provides code for the configuration
  *          of the USART instances.
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include <stdio.h>
#include <string.h>
#include "usart.h"

/* USER CODE BEGIN 0 */
uint8_t rx_buffer[RX_BUFFER_SIZE];
volatile uint16_t rx_size = 0;
volatile uint8_t rx_complete = 0;
volatile uint8_t dma_active = 0; // 新增：DMA活动标志
/* USER CODE END 0 */

UART_HandleTypeDef huart1;
DMA_HandleTypeDef hdma_usart1_rx;
DMA_HandleTypeDef hdma_usart1_tx;

/* USART1 init function */

void MX_USART1_UART_Init(void)
{

  /* USER CODE BEGIN USART1_Init 0 */

  /* USER CODE END USART1_Init 0 */

  /* USER CODE BEGIN USART1_Init 1 */

  /* USER CODE END USART1_Init 1 */
  huart1.Instance = USART1;
  huart1.Init.BaudRate = 115200;
  huart1.Init.WordLength = UART_WORDLENGTH_8B;
  huart1.Init.StopBits = UART_STOPBITS_1;
  huart1.Init.Parity = UART_PARITY_NONE;
  huart1.Init.Mode = UART_MODE_TX_RX;
  huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart1.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart1) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART1_Init 2 */
    // 配置并启动DMA接收（环形缓冲区模式）
    HAL_UARTEx_ReceiveToIdle_DMA(&huart1, rx_buffer, RX_BUFFER_SIZE);
    __HAL_UART_ENABLE_IT(&huart1, UART_IT_IDLE); // 使能空闲线路中断
    dma_active = 1; // 标记DMA已启动
    // 启动接收中断（首次接收1字节触发中断）
//    HAL_UART_Receive_IT(&huart1, &rx_buffer[0], 1);
  /* USER CODE END USART1_Init 2 */

}

void HAL_UART_MspInit(UART_HandleTypeDef* uartHandle)
{

  GPIO_InitTypeDef GPIO_InitStruct = {0};
  if(uartHandle->Instance==USART1)
  {
  /* USER CODE BEGIN USART1_MspInit 0 */

  /* USER CODE END USART1_MspInit 0 */
    /* USART1 clock enable */
    __HAL_RCC_USART1_CLK_ENABLE();

    __HAL_RCC_GPIOA_CLK_ENABLE();
    /**USART1 GPIO Configuration
    PA9     ------> USART1_TX
    PA10     ------> USART1_RX
    */
    GPIO_InitStruct.Pin = GPIO_PIN_9;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    GPIO_InitStruct.Pin = GPIO_PIN_10;
    GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    /* USART1 DMA Init */
    /* USART1_RX Init */
    hdma_usart1_rx.Instance = DMA1_Channel5;
    hdma_usart1_rx.Init.Direction = DMA_PERIPH_TO_MEMORY;
    hdma_usart1_rx.Init.PeriphInc = DMA_PINC_DISABLE;
    hdma_usart1_rx.Init.MemInc = DMA_MINC_ENABLE;
    hdma_usart1_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
    hdma_usart1_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
    hdma_usart1_rx.Init.Mode = DMA_CIRCULAR; // 环形模式
    hdma_usart1_rx.Init.Priority = DMA_PRIORITY_LOW;
    if (HAL_DMA_Init(&hdma_usart1_rx) != HAL_OK)
    {
      Error_Handler();
    }
      __HAL_LINKDMA(uartHandle,hdmarx,hdma_usart1_rx);


    /* USART1_TX Init */
    hdma_usart1_tx.Instance = DMA1_Channel4;
    hdma_usart1_tx.Init.Direction = DMA_MEMORY_TO_PERIPH;
    hdma_usart1_tx.Init.PeriphInc = DMA_PINC_DISABLE;
    hdma_usart1_tx.Init.MemInc = DMA_MINC_ENABLE;
    hdma_usart1_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
    hdma_usart1_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
    hdma_usart1_tx.Init.Mode = DMA_NORMAL;
    hdma_usart1_tx.Init.Priority = DMA_PRIORITY_LOW;
    if (HAL_DMA_Init(&hdma_usart1_tx) != HAL_OK)
    {
      Error_Handler();
    }

    __HAL_LINKDMA(uartHandle,hdmatx,hdma_usart1_tx);

    /* USART1 interrupt Init */
    HAL_NVIC_SetPriority(USART1_IRQn, 5, 0);
    HAL_NVIC_EnableIRQ(USART1_IRQn);
  /* USER CODE BEGIN USART1_MspInit 1 */

  /* USER CODE END USART1_MspInit 1 */
  }
}

void HAL_UART_MspDeInit(UART_HandleTypeDef* uartHandle)
{

  if(uartHandle->Instance==USART1)
  {
  /* USER CODE BEGIN USART1_MspDeInit 0 */

  /* USER CODE END USART1_MspDeInit 0 */
    /* Peripheral clock disable */
    __HAL_RCC_USART1_CLK_DISABLE();

    /**USART1 GPIO Configuration
    PA9     ------> USART1_TX
    PA10     ------> USART1_RX
    */
    HAL_GPIO_DeInit(GPIOA, GPIO_PIN_9|GPIO_PIN_10);

    /* USART1 DMA DeInit */
    HAL_DMA_DeInit(uartHandle->hdmarx);
    HAL_DMA_DeInit(uartHandle->hdmatx);

    /* USART1 interrupt Deinit */
    HAL_NVIC_DisableIRQ(USART1_IRQn);
  /* USER CODE BEGIN USART1_MspDeInit 1 */

  /* USER CODE END USART1_MspDeInit 1 */
  }
}
/* USER CODE BEGIN 1 */
/**
 * @brief 空闲线路中断处理（将在stm32f1xx_it.c USART1_IRQHandler中调用）
 */
void USART1_IdleCallback(void)
{
    if (dma_active) { // 确保DMA处于活动状态
        // 清除空闲标志
        __HAL_UART_CLEAR_IDLEFLAG(&huart1);

        // 停止当前的DMA接收（重要！防止重复触发）
        HAL_UART_DMAStop(&huart1);
        dma_active = 0;

        // 计算接收数据大小
        uint16_t size = RX_BUFFER_SIZE - __HAL_DMA_GET_COUNTER(&hdma_usart1_rx);

        // 调用回调函数
        HAL_UARTEx_RxEventCallback(&huart1, size);
    }
}


// 接收事件回调函数
void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{
    if(huart->Instance == USART1)
    {
        rx_size = Size;
        rx_complete = 1; // 标记接收完成

        // 处理完整数据帧（示例：回显数据）
        // 在发送前确保不接收自己发送的数据
        HAL_UART_Transmit(&huart1, rx_buffer, rx_size, HAL_MAX_DELAY);

        // 重新启动DMA接收
        HAL_UARTEx_ReceiveToIdle_DMA(&huart1, rx_buffer, RX_BUFFER_SIZE);
        dma_active = 1;
    }
}
// 错误回调函数
void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart)
{
    if(huart->Instance == USART1)
    {
        // 清除错误标志
        __HAL_UART_CLEAR_FLAG(huart, UART_FLAG_ORE);

        // 停止并重新启动DMA接收
        HAL_UART_DMAStop(&huart1);
        HAL_UARTEx_ReceiveToIdle_DMA(&huart1, rx_buffer, RX_BUFFER_SIZE);
        dma_active = 1;

        // 可以添加其他错误处理逻辑
    }
}
/**
 * @brief 检查是否有完整数据帧接收完成
 * @return 1-有完整数据，0-没有
 */
uint8_t UART1_HasData(void)
{
    return rx_complete;
}
/**
 * @brief 获取接收到的数据
 * @param buffer 存储数据的缓冲区
 * @param max_size 缓冲区最大大小
 * @return 实际接收到的数据大小
 */
uint16_t UART1_GetData(uint8_t *buffer, uint16_t max_size)
{
    uint16_t size = (rx_size < max_size) ? rx_size : max_size;
    memcpy(buffer, rx_buffer, size);
    rx_complete = 0; // 清除接收完成标志
    return size;
}

/**
 * @brief 发送数据（阻塞模式）
 * @param data 要发送的数据缓冲区
 * @param size 数据大小（字节）
 * @param timeout 超时时间（毫秒）
 */
void UART1_Transmit(uint8_t *data, uint16_t size, uint32_t timeout)
{
    // 停止DMA接收，防止发送数据时触发接收中断
    if (dma_active) {
        HAL_UART_DMAStop(&huart1);
        dma_active = 0;
    }

    HAL_StatusTypeDef status = HAL_UART_Transmit(&huart1, data, size, timeout);

    // 发送完成后重新启动DMA接收
    HAL_UARTEx_ReceiveToIdle_DMA(&huart1, rx_buffer, RX_BUFFER_SIZE);
    dma_active = 1;
}
/* USER CODE END 1 */
